<?php
/**
 * Created by PhpStorm.
 * User: FoxxxZhu
 * Date: 2018/2/7
 * Time: 16:10
 */

namespace Forxx\Api;


use App\Dao\VideoVisitLogTable;
use Forxx\Dao\CategoryTable;
use Forxx\Dao\TagsTable;
use Forxx\Dao\V2tagTable;
use Forxx\Dao\VideoResTable;
use Forxx\Dao\VideoTable;
use Forxx\RedisCache;
use Lavender\Core;
use Lavender\Db\Expression;
use Lavender\IdMaker;

class Video {

    const VISIT_COUNT_KEY = "video::visit::";
    const RELATION_NOT_EXIST_KEY = "relation::not_exist";

    public static function addTag($tag,$vid){
        $cat = TagsTable::instance()->get(null,[],['name'=>$tag],null,0,1);
        if(count($cat) > 0){
            TagsTable::instance()->update($cat[0]['id'],[new Expression("num = num + 1")]);
            $tid = $cat[0]['id'];
        }
        else{
            $tid = IdMaker::make("video");
            TagsTable::instance()->add($tid ,['name'=>$tag]);
        }
        V2tagTable::instance()->add(null,['vid'=>$vid,'tid'=>$tid]);
    }

    public static function add($params){
        $itemRes = [
            'type'=> 1,
            'rid'=> $params['rid'],
            'source'=> $params['source'],
        ];
        $origin = VideoResTable::instance()->get(null,[],$itemRes);
        if(isset($origin[0])){
            if($params['cat_id'] != 0 && $params['cat_id'] != 9999){
                VideoTable::instance()->update($origin[0]['id'],['cat_id'=>$params['cat_id']]);
            }
            return $origin[0];
        }
        $fileInfo = FileCDN::saveRemoteImage($params['poster'],"jpg");
        $poster = isset($fileInfo['file'])?$fileInfo['file']:$params['poster'];
        $id = IdMaker::make("video");
        $nowDatetime = date("Y-m-d H:i:s");
        $item = [
            'title'=> $params['title'],
            'duration'=> $params['duration'],
            'visit'=> $params['views'],
            'uid'=> $params['uid'],
            'cat_id'=> $params['cat_id'],
            'is_hd'=> $params['is_hd'],
            'poster'=> $poster,
            'updated'=> $nowDatetime,
            'created'=> $nowDatetime,
        ];
        VideoTable::instance()->add($id,$item);
        VideoResTable::instance()->add($id,$itemRes);
        if(is_array($params['tags']) && count($params['tags']) > 0){
            foreach($params['tags'] as $tag){
               self::addTag($tag,$id);
            }
        }
        return ['id'=>$id];
    }

    public static function detail($id){
        $info = VideoTable::instance()->get_single($id);
        return $info;
    }

    public static function getHotCat($size){
        $cat = CategoryTable::instance()->get(null,[],[],"num DESC",0,$size);
        return $cat;
    }

    public static function getMenu($size){
        $cat = CategoryTable::instance()->get(null,[],['is_menu'=>1],"num DESC",0,$size);
        return $cat;
    }

    public static function getByCat($params,$page = 1,$size = 20){
        $size  = abs($size) ;
        $size  = $size < 0 ? 20 : ($size > 1000 ) ? 1000 : $size;
        $offset = ($page - 1 ) * $size;
        $offset = $offset < 0 ? 0 : $offset;
        $condition = ['cat_id' => $params['id']];
        if(isset($params['is_hd'])){
            $condition = ['is_hd' => $params['is_hd']];
        }
        $between = [];
        if(isset($params['min_time'])){
            $between[] = ['duration','>',$params['min_time']];
        }
        if(isset($params['max_time']) && $params['max_time'] > 0){
            $between[] = ['duration','<=',$params['max_time']];
        }
        if(count($between) > 0){
            $condition['between'] = Expression::MakeCompare($between);
        }
        $orderStr = "created DESC";
        if(isset($params['order']) && in_array($params['order'],['created','visit']))
        {
            $orderStr = $params['order']." DESC";
        }
        $res = VideoTable::instance()->get(null,[],$condition,$orderStr,$offset,$size);
        return $res;
    }

    public static function getByIds($ids){
        $videos = VideoTable::instance()->get($ids);
        $res = Utils::sort_by_given_ids($videos,$ids);
        return $res;
    }

    public static function getVisitLog($page = 1,$size = 20){
        $ids = VisitLog::instance()->get($size,$page);
        return $ids;
    }

    public static function getHotList($page = 1,$size = 20){
        $size  = abs($size) ;
        $size  = $size < 0 ? 20 : ($size > 1000 ) ? 1000 : $size;
        $offset = ($page - 1 ) * $size;
        $offset = $offset < 0 ? 0 : $offset;
        $videos = VideoTable::instance()->get(null,[],[],"visit DESC",$offset,$size);
        return $videos;
    }
    public static function getLastUploadList($page = 1,$size = 20){
        $size  = abs($size) ;
        $size  = $size < 0 ? 20 : ($size > 1000 ) ? 1000 : $size;
        $offset = ($page - 1 ) * $size;
        $offset = $offset < 0 ? 0 : $offset;
        $videos = VideoTable::instance()->get(null,[],[],"created DESC",$offset,$size);
        return $videos;
    }

    public static function addVisit($id,$num = 1)
    {
        VideoTable::instance()->update($id,[Expression::MakeRaw("`visit` = `visit` + {$num}")]);
    }

    public static function pushRelationNotExist($id,$info){
        $data = ['id'=>$id,'detail'=>$info];
        $key = self::RELATION_NOT_EXIST_KEY;
        $jsonData = RedisCache::instance()->pack($data);
        RedisCache::instance()->rpush($key,$jsonData);
    }

    public static function popRelationNotExist(){
        $key = self::RELATION_NOT_EXIST_KEY;
        $data = RedisCache::instance()->lpop($key);
        if($data){
            return  RedisCache::instance()->unpack($data);
        }
        return null;
    }

    public static function addVisitLog($id,$ip,$uid){
        VideoVisitLogTable::instance()->add(null,[
            'vid'=>$id,
            'ip'=>$ip,
            'uid'=>$uid,
            'created'=>Utils::get_datetime(),
        ]);
    }
}